<template>
  <div class="adoption-browse">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>宠物领养浏览</h1>
        <p>为这些可爱的小生命找到温暖的家</p>
      </div>
      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="类型">
            <el-input v-model="filterForm.type" placeholder="请输入类型" clearable></el-input>
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="filterForm.name" placeholder="请输入名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="品种">
            <el-input v-model="filterForm.breed" placeholder="请输入品种" clearable></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="filterForm.status" placeholder="请选择" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="可领养" :value="1" />
              <el-option label="申请中" :value="2" />
              <el-option label="已领养" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">筛选</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 宠物列表 -->
      <el-card v-if="loading" class="loading-card">
        <div class="loading-content">
          <i class="el-icon-loading"></i>
          <span>加载中...</span>
        </div>
      </el-card>

      <!-- 空状态 -->
      <div v-else-if="pets.length === 0" class="empty-state">
        <div class="empty-icon">🐾</div>
        <h3>暂无宠物信息</h3>
        <p>目前没有可领养的宠物，请稍后再来看看</p>
      </div>

      <div v-else class="pets-grid">
        <div class="pet-card" v-for="pet in pets" :key="pet.id">
          <div class="pet-image">
            <img :src="pet.image" :alt="pet.name" />
            <div class="pet-status" :class="returnText(pet.status)">
              {{ getStatusText(pet.status) }}
            </div>
          </div>

          <div class="pet-info">
            <h3>{{ pet.name }}</h3>
            <div class="pet-details">
              <span class="detail-item">
                <i class="el-icon-star-on"></i>
                {{ getTypeText(pet.type) }}
              </span>
              <span class="detail-item">
                <i class="el-icon-time"></i>
                {{ getAgeText(pet.age) }}
              </span>
              <span class="detail-item">
                <i class="el-icon-user"></i>
                {{ getGenderText(pet.gender) }}
              </span>
            </div>
            <p class="pet-description">{{ pet.description }}</p>

            <div class="pet-actions">
              <el-button type="primary" size="mini" @click="viewDetails(pet)" icon="el-icon-info">
                详情
              </el-button>
              <el-button v-if="isLoggedIn" type="success" size="mini" @click="applyAdoption(pet)"
                :disabled="!isPetAvailable(pet)" icon="el-icon-check">
                领养
              </el-button>
              <el-button v-else type="info" size="mini" @click="goToLogin">
                登录后申请
              </el-button>
              <el-button v-if="isLoggedIn" type="warning" size="mini" @click="addToFavorites(pet)" circle>
                <i class="el-icon-star-off" v-if="!pet.isCollection"></i>
                <i class="el-icon-star-on" v-else></i>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[12, 24, 48]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="totalPets">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getAllPets } from '../api/pet'
import { addAdoption } from '@/api/adoption-record'
import { addPetRescue, cancelCollection } from '@/api/pet-collection'



export default {
  name: 'AdoptionBrowse',

  computed: {
    ...mapGetters(['isLoggedIn', 'user']),
  },

  data() {
    return {
      loading: false,
      currentPage: 1,
      pageSize: 12,
      totalPets: 0,

      filterForm: {
        type: '',
        age: '',
        gender: ''
      },

      pets: []
    }
  },

  mounted() {
    this.loadPets()
  },

  methods: {
    async loadPets() {
      this.loading = true
      try {
        // 构建查询参数
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...this.filterForm
        }

        // 移除空值参数
        Object.keys(params).forEach(key => {
          if (params[key] === '' || params[key] === null || params[key] === undefined) {
            delete params[key]
          }
        })

        const response = await getAllPets(params)
        if (response.data && response.code === 200) {
          this.pets = response.data.rows || []
          this.totalPets = response.data.total || 0
        } else {
          this.pets = []
          this.totalPets = 0
        }
      } catch (error) {
        this.pets = []
        this.totalPets = 0
      } finally {
        this.loading = false
      }
    },

    handleFilter() {
      this.currentPage = 1
      this.loadPets()
    },

    resetFilter() {
      this.filterForm = {
        type: '',
        age: '',
        gender: ''
      }
      this.currentPage = 1
      this.loadPets()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadPets()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.loadPets()
    },

    viewDetails(pet) {
      this.$router.push(`/pet-detail/${pet.id}`)
    },

    applyAdoption(pet) {
      if (!this.isLoggedIn) {
        this.$message.warning('请先登录后再申请领养')
        this.$router.push('/login')
        return
      }

      this.$confirm(`确定要申请领养 ${pet.name} 吗？`, '确认申请', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(async () => {
        const res = await addAdoption({
          petId: pet.id,
          userId: this.user.id,
          ...pet
        })
        if (res.code === 200) {
          this.$message({
            message: '领养申请已提交',
            type: 'success'
          })
          this.$router.push('/my-applications')
        } else {
          this.$message({
            message: res.msg || '领养申请失败',
            type: 'error'
          })
        }
      }).catch(() => {
        // 用户取消
      })
    },

    goToLogin() {
      this.$message.info('请先登录后再申请领养')
      this.$router.push('/login')
    },

    getTypeText(type) {
      const typeMap = {
        dog: '狗狗',
        cat: '猫咪',
        other: '其他'
      }
      return typeMap[type] || type
    },

    getAgeText(age) {
      const ageMap = {
        young: '幼年',
        adult: '成年',
        senior: '老年'
      }
      return ageMap[age] || age
    },

    getGenderText(gender) {
      const genderMap = {
        male: '公',
        female: '母'
      }
      return genderMap[gender] || gender
    },

    returnText(status) {
      if (status === 1) {
        return 'available'
      } else if (status === 2) {
        return 'pending'
      } else if (status === 3) {
        return 'adopted'
      }
      return status
    },

    getStatusText(status) {
      const statusMap = {
        1: '可领养',
        2: '申请中',
        3: '已领养',
      }
      return statusMap[status] || status
    },

    // 检查宠物是否可申请领养
    isPetAvailable(pet) {
      return pet.status === 1
    },

    // 添加到收藏
    async addToFavorites(pet) {
      try {
        if (pet.isCollection) {
          // 取消收藏
          const res = await cancelCollection({ petId: pet.id })
          if (res.code === 200) {
            // 更新宠物的收藏状态
            pet.isCollection = false
            this.$message({
              message: '取消收藏成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: res.msg || '取消收藏失败',
              type: 'error'
            })
          }
          return
        }
        const params = {
          userId: this.user.userId,
          userName: this.user.userName,
          petId: pet.id,
          ...pet
        }
        const res = await addPetRescue(params)
        if (res.code === 200) {
          // 更新宠物的收藏状态
          pet.isCollection = true
          this.$message({
            message: '收藏成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: res.msg || '收藏失败',
            type: 'error'
          })
        }
      } catch (error) {
        console.error('收藏失败:', error)
        this.$message({
          message: '收藏失败，请稍后重试',
          type: 'error'
        })
      }
    }
  }
}
</script>

<style scoped>
.adoption-browse {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px 0;
}






.filter-form {
  margin: 0;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 12px;
  margin: 20px 0;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.empty-state h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.empty-state p {
  color: #666;
  font-size: 16px;
  line-height: 1.5;
}

.pets-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.pet-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.pet-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.pet-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.pet-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.pet-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
  color: white;
}

.pet-status.available {
  background: #67C23A;
}

.pet-status.pending {
  background: #E6A23C;
}

.pet-status.adopted {
  background: #909399;
}

.pet-info {
  padding: 20px;
}

.pet-info h3 {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
}

.pet-details {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.detail-item i {
  margin-right: 5px;
  color: #409EFF;
}

.pet-description {
  color: #666;
  line-height: 1.5;
  margin-bottom: 20px;
  font-size: 14px;
}

.pet-actions {
  display: flex;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
</style>